package cn.wolfcode.luowowo.website.controller;

import cn.wolfcode.luowowo.article.domain.Destination;
import cn.wolfcode.luowowo.article.domain.StrategyDetail;
import cn.wolfcode.luowowo.article.domain.Travel;
import cn.wolfcode.luowowo.article.domain.TravelContent;
import cn.wolfcode.luowowo.article.query.TravelQuery;
import cn.wolfcode.luowowo.article.service.IDestinationService;
import cn.wolfcode.luowowo.article.service.IStrategyDetailService;
import cn.wolfcode.luowowo.article.service.IStrategyService;
import cn.wolfcode.luowowo.article.service.ITravelService;
import cn.wolfcode.luowowo.comment.domain.TravelComment;
import cn.wolfcode.luowowo.comment.query.TravelCommentQuery;
import cn.wolfcode.luowowo.comment.service.ITravelCommentService;
import cn.wolfcode.luowowo.common.util.JsonResult;
import cn.wolfcode.luowowo.common.util.KeysUtil;
import cn.wolfcode.luowowo.member.domain.UserInfo;
import cn.wolfcode.luowowo.service.ITravelStatisRedisService;
import cn.wolfcode.luowowo.vo.StatisVO;
import cn.wolfcode.luowowo.website.annotation.RequireLogin;
import cn.wolfcode.luowowo.website.annotation.UserParam;
import cn.wolfcode.luowowo.website.util.UMEditorUploader;
import com.alibaba.dubbo.config.annotation.Reference;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Controller
@RequestMapping("travel")
public class TravelController {

    @Reference
    private ITravelService travelService;

    @Reference
    private IStrategyService strategyService;

    @Reference
    private IDestinationService destinationService;

    @Reference
    private IStrategyDetailService strategyDetailService;

    @Reference
    private ITravelCommentService travelCommentService;

    @Reference
    private ITravelStatisRedisService statisRedisService;

    /**
     * 游记列表
     * @param qo
     * @param model
     * @return
     */
    @RequestMapping("")
    public String list(@ModelAttribute("qo")TravelQuery qo, Model model){
        model.addAttribute("pageInfo", travelService.queryForList(qo));
        //todo 最新游记动态的显示
        List<TravelComment> tcs = travelCommentService.findFirstTen();

        model.addAttribute("tcs", tcs);

        return "travel/list";
    }

    /**
     * 游记明细
     * @param id
     * @param model
     * @return
     */
    @RequestMapping("detail")
    public String detail(Long id,Model model,@UserParam UserInfo userInfo,@ModelAttribute("qo")TravelCommentQuery qo){
        Travel travel = travelService.getTravelById(id);
        TravelContent travelContent = travelService.getContent(id);
        if (travel != null) {
            travel.setTravelContent(travelContent);
        }

        ///没有登录或者不是本人的话不显示编辑
        UserInfo author = travel.getAuthor();
        if (userInfo == null || author.getId()!=userInfo.getId()){
            author.setId(-1L);
            travel.setAuthor(author);
        }

        //操作阅读数和显示统计数
        statisRedisService.statisAndUpdateViewnum(id, 1, StatisVO.USER_FAVOR_TRAVEL);



        model.addAttribute("detail", travel);


        //关联目的地
        Long destId = travel.getDest().getId();
        List<Destination> destinations = destinationService.creatToasts(destId);
        model.addAttribute("toasts", destinations);

        //相关攻略
        List<StrategyDetail> detailTop3 = strategyDetailService.getDetailTop3(destId);
        model.addAttribute("sds", detailTop3);

        //相关游记
        List<Travel> ts = travelService.getTravelTop3ByCreatTime(destId);
        model.addAttribute("ts", ts);

        //相关游记评论
        qo.setTravelId(id);
        List list = travelCommentService.query(qo);
        model.addAttribute("list", list);

        //判断是否收藏 页面回显
        model.addAttribute("vo", statisRedisService.getStatisRedis(KeysUtil.TRAVEL_STATIS_VO.join(id.toString())));
        if (userInfo != null){
            boolean isFavor = statisRedisService.checkFavor(id,
                    KeysUtil.USER_TRAVEL_STATIS_FAVOR.join(id.toString()));
            model.addAttribute("isFavor", isFavor);
        }
        return "travel/detail";
    }

    /**
     * 游记编辑  没有登录不让保存
     * @return
     */
    @RequireLogin
    @RequestMapping("input")
    public String input(Long id,Model model){
        //编辑的时候数据回显
        if (id != null) {
            //tv内容回显
            Travel travel = travelService.get(id);
            TravelContent content = travelService.getContent(id);
            travel.setTravelContent(content);
            model.addAttribute("tv", travel);
        }
        //dests
        model.addAttribute("dests", destinationService.getDestByDeep(3));
        return "travel/input";
    }


    /**
     * 保存或者更新
     * @param travel
     * @param userInfo
     * @return
     */
    @RequestMapping("saveOrUpdate")
    @ResponseBody
    public Object saveOrUpdate(Travel travel, @UserParam UserInfo userInfo){
        //当用户没有登录的时候,提示登录
        if (userInfo == null) {
            return new JsonResult(false, "操作游记需要登录哦");
        }
        //当前用户
        travel.setAuthor(userInfo);
        Long id = travelService.saveOrUpdate(travel);
        return new JsonResult(true, "成功了", id);
    }



    @Value("${file.path}")
    private String filePath;
    //上传图片
    @RequestMapping("/contentImage")
    @ResponseBody
    public String uploadUEImage(MultipartFile upfile, HttpServletRequest request) throws Exception{
        UMEditorUploader up = new UMEditorUploader(request);
        String[] fileType = {".gif" , ".png" , ".jpg" , ".jpeg" , ".bmp"};
        up.setAllowFiles(fileType);
        up.setMaxSize(10000); //单位KB
        up.upload(upfile, filePath);

        String callback = request.getParameter("callback");
        String result = "{\"name\":\""+ up.getFileName() +"\", \"originalName\": \""+ up.getOriginalName() +"\", \"size\": "+ up.getSize()
                +", \"state\": \""+ up.getState() +"\", \"type\": \""+ up.getType() +"\", \"url\": \""+ up.getUrl() +"\"}";
        result = result.replaceAll( "\\\\", "\\\\" );
        if(callback == null ){
            return result ;
        }else{
            return "<script>"+ callback +"(" + result + ")</script>";
        }
    }


    @RequestMapping("unLogin")
    @ResponseBody
    public Object unLogin(){
        return "";
    }

    //发表评论游记
    @RequireLogin
    @RequestMapping("commentAdd")
    public String  commentAdd(TravelComment comment,int floor,Model model,@UserParam UserInfo userInfo){
        comment.setCity(userInfo.getCity());
        comment.setHeadUrl(userInfo.getHeadImgUrl());
        comment.setUserId(userInfo.getId());
        comment.setUsername(userInfo.getNickname());
        comment.setLevel(userInfo.getLevel());
        TravelComment travelComment = travelCommentService.saveOrUpdate(comment);
        model.addAttribute("c", travelComment);
        model.addAttribute("floor", floor + 1);
        return "travel/commentTpl";
    }


    @RequestMapping("favor")
    @ResponseBody
    public Object favor(Long sid, @UserParam UserInfo userInfo) {
        return userInfo == null ? JsonResult.UNLOGIN : statisRedisService.favor(sid, userInfo.getId(),StatisVO.USER_FAVOR_TRAVEL);
    }

    @RequestMapping("travelThumbup")
    @ResponseBody
    public Object strategyThumbup(Long sid, @UserParam UserInfo userInfo) {
        return userInfo == null ? JsonResult.UNLOGIN : statisRedisService.strategyThumbup(sid, userInfo.getId(),StatisVO.USER_FAVOR_TRAVEL);
    }

}
